package com.example.microservice.common.exception;

import com.example.microservice.common.exception.enums.ExceptionType;
import com.example.microservice.common.exception.pojo.ApiErrorResponse;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @Author: caohuijie
 * @Date: 创建日期 2018/11/13
 * @Modified By:
 * @Description: 全局异常处理类
 */
@RestControllerAdvice
public class GlobalControllerExceptionHandler {


    /**
     * 参数不是预期类型的时候
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex){

        ApiErrorResponse response = new ApiErrorResponse.ApiErrorResponseBuilder()
                .withStatus(HttpStatus.BAD_REQUEST)
                .withError_code(HttpStatus.BAD_REQUEST.name())
                .withMessage(ex.getMessage())
                .build();
        return new ResponseEntity(response,HttpStatus.BAD_GATEWAY);

    }

    /**
     * API无法读取HTTP消息时
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    @ResponseBody
    protected ResponseEntity handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        ApiErrorResponse response = new ApiErrorResponse.ApiErrorResponseBuilder()
                .withStatus(HttpStatus.BAD_GATEWAY)
                .withError_code(ExceptionType.MALFORMED_JSON_REQUEST.getCode())
                .withMessage(ex.getLocalizedMessage())
                .withDetail(ExceptionType.MALFORMED_JSON_REQUEST.getMessage() + ex.getMessage()).build();
        return new ResponseEntity(response, HttpStatus.BAD_GATEWAY);
    }




    /**
     * 服务器异常的处理，返回500
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity handleException(Exception ex) {

        ApiErrorResponse response = new ApiErrorResponse.ApiErrorResponseBuilder()
                .withStatus(HttpStatus.INTERNAL_SERVER_ERROR)
                .withError_code(ExceptionType.INTERNAL_SERVER_ERROR.getCode())
                .withMessage(ex.getLocalizedMessage())
                .withDetail(ExceptionType.INTERNAL_SERVER_ERROR.getMessage() + ex.getMessage()).build();
        return new ResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }


}
